package com.manning.readinglist.controller;

import com.manning.readinglist.dao.IBookRepository;
import com.manning.readinglist.entity.Book;
import com.tul.cusa.common.util.ListUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * 控制器
 * @author tuliang
 */
@Controller
@RequestMapping("/readingList")
public class ReadingListController {

    private IBookRepository readingListRepository;

    @Autowired
    public ReadingListController(IBookRepository readingListRepository) {
        this.readingListRepository = readingListRepository;
    }

    @RequestMapping(value="/{reader}", method = RequestMethod.GET)
    public String readersBooks(@PathVariable("reader") String reader, Model model){
        List<Book> readingList = readingListRepository.findByReader(reader);

        if (ListUtil.isNotEmpty(readingList)) {
            model.addAttribute("books", readingList);
        }

        return "readingList";
    }

    @RequestMapping(value = "/{reader}", method = RequestMethod.POST)
    public String addToReadingList(@PathVariable("reader") String reader, Book book) {
        book.setReader(reader);
        readingListRepository.save(book);
        return "redirect:/readingList/{reader}";
    }
}
